const db = require('../db/index')

// 获取商品列表的处理函数
exports.getMall = (req, res) => {
    const sql = `select * from mall order by id desc`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            code: 20000,
            message: '获取商品数据成功!',
            data: results
        })
    })
}

// 新增商品的处理函数
exports.addMall = (req, res) => {
    const sql = `insert into mall set ?`
    db.query(sql, req.body, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('新增商品失败')
        res.cc('新增商品成功!', 0, 20000)
    })
}

// 根据id修改商品的处理函数
exports.editMall = (req, res) => {
    const sql = `update mall set ? where id = ?`
    db.query(sql, [req.body, req.body.id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('更新商品失败!')
        res.cc('更新商品成功!', 0, 20000)
    })
}

// 根据id删除商品的处理函数
exports.deleteMall = (req, res) => {
    const sql = `delete from mall where id=?`
    db.query(sql, req.params.id, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows === 1) {
            res.cc('删除用户成功!', 0, 20000)
        }
    })
}

// 根据商品名称获取商品的处理函数
exports.getMallByName = (req, res) => {
    const sql = `select * from mall where name like ?`
    db.query(sql, req.body.name + '%', (err, results) => {
        console.log(req)
        if (err) return res.cc(err)
        res.send({
            status: 0,
            code: 20000,
            message: '获取商品成功!',
            data: results,
        })
    })
}
